package com.homeWorkMapReduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;

import java.io.IOException;

/**
 * @description:
 * @projectName: hadoopstudy
 * @see: com.homeWorkMapReduce
 * @author: 崔宗祺
 * @createTime: 2024/5/17 9:06
 * @version: 1.0
 */
public class ScoreMapReduce extends Configured {
    static class ScoreMap extends Mapper<IntWritable, Text, Text, Text> {
        @Override
        protected void map(IntWritable key, Text value, Mapper<IntWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            String[] split = value.toString().split(",");
            String studentId = split[0];
            String className = studentId.startsWith("1") ? "一班" : "二班";
            String name = split[1];
            String subject = split[2];
            context.write(new Text(className + " " + name), new Text(studentId + " " + subject + ":" + split[2]));
        }
    }

    static class ScoreReduce extends Reducer<Text, Text, Text, Text> {
        @Override
        protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            String studentInfo = "";
            int totalScore = 0;

            for (Text value : values) {
                studentInfo += value.toString() + " ";
                totalScore += Integer.parseInt(value.toString().split(":")[1]);
            }

            context.write(key, new Text(studentInfo + " 总分:" + totalScore));
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "Score Calculation");

        job.setJarByClass(ScoreMapReduce.class);
        job.setMapperClass(ScoreMap.class);
        job.setReducerClass(ScoreReduce.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

}
